import { FileOutlined, FolderOpenOutlined } from '@ant-design/icons';
import { Breadcrumb, Button, message, Image } from 'antd';
import { InfinityTable } from 'antd-table-infinity';
import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { deleteFile, fileList } from './service';
import ConfirmOperation from '@/components/ConfirmOperation'
import Style from './style.less'
import { useLocation } from 'umi';

let callback = () => {

}

const TableList: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [sureTip, setSureTip] = useState<string>('此操作会让文件永久丢失，是否继续？');
  const actionRef = useRef<ActionType>();
  const confirmOperationRef = useRef();
  // 表格数据
  const [data, setData] = useState([]);
  // 是否到底
  const [isEnd, setIsEnd] = useState(false);
  // 下一个请求文件的开始位置
  const [netxFile, setNetxFile] = useState('');
  const [loading, setLoading] = useState(false);
  // 加载请求大小
  const pageSize = 30

  const location = useLocation();
  // console.log(location.query.path)
  const [path, setPath] = useState(location?.query?.path || '');
  // const [searchParams, setSearchParams] = useSearchParams();

  useEffect(() => {
    if (!isEnd) {
      getData();
    }
  }, [isEnd]);

  /**
   * 获取数据
   */
  const getData = async () => {
    if (!isEnd) {
      setLoading(true)
      const res = await fileList({
        'prefix': path,
        'ossMaxKeys': pageSize,
        'ossMarker': netxFile
      })

      const list = data.concat(res.list.map((item, index) => {
        item.index = data.length + index + 1
        return item
      }))
      setData(list)
      setIsEnd(res.is_end)
      setNetxFile(res.next)
      setLoading(false)
    }

  }

  let pageReloaddata = (filePath: string) => {
    setPath(filePath)
    setData([])
    setNetxFile('')
    setIsEnd(false)

  }

  const BreadcrumbBox = () => {
    const pathList = path.split('/')
    pathList.pop()
    // console.log(pathList);
    const onClick = (index: number): any => {
      return () => {
        const filePath = pathList.slice(0, index + 1).join('/') + '/'
        // history.push({ pathname: '/file/list', query: { path: filePath } })
        pageReloaddata(filePath)
      }
    }
    const BreadcrumbItemList = pathList.map((item, index) => (
      <Breadcrumb.Item key={index}>
        <a onClick={onClick(index)}>{item}</a>
      </Breadcrumb.Item>
    ))
    // console.log(BreadcrumbItemList);

    return (
      <Breadcrumb>

        <Breadcrumb.Item> <a onClick={() => {
          pageReloaddata('')
        }}>Home</a></Breadcrumb.Item>
        {BreadcrumbItemList}
      </Breadcrumb>
    )
  }

  const columns: ProColumns[] = [
    {
      width: 50,
      title: '序号',
      search: false,
      dataIndex: 'index',
    },
    {
      width: 50,
      search: false,
      ellipsis: true,
      render: (_: any, record) => [
        record.dir ? <FolderOpenOutlined key="dir" /> : <FileOutlined key="dir" />
      ]
    },
    {
      title: '文件名',
      dataIndex: 'name',
      ellipsis: true,

      render: (_: any, record) => record.dir ? <a onClick={() => {
        // history.push({ pathname: '/file/list', query: { path: path + record.name } })
        pageReloaddata(path + record.name)
      }}>
        {record.name}</a> : <span>{record.name}</span>
    },
    {
      title: '预览',
      dataIndex: 'url',
      render: (val: any) => <Image width={60} height={60} src={val}></Image>,
    },
    {
      title: '文件大小',
      dataIndex: 'size',
      search: false,
    },
    {
      title: '最后修改时间',
      dataIndex: 'timeModified',
      ellipsis: true,
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 200,
      render: (_: any, record) => [
        <Button type="link" key="delete" danger onClick={() => {
          let tempFn = () => {
            deleteFile({ path: record.path, type: record.dir ? 2 : 1 }).then(() => {
              message.success('删除成功');
              pageReloaddata(path)
            }).catch(() => {
              message.error('删除失败');
            });
          }

          setSureTip('改操作会导致资源永久丢失，是否继续操作？')
          callback = tempFn
          confirmOperationRef?.current?.showModal()
          return

        }}>
          彻底删除
        </Button>
      ],
    },
  ];

  return (
    <PageContainer key={path}>
      <div className={Style.breadcrumbBottom}>
        {BreadcrumbBox()}
      </div>

      <InfinityTable columns={columns} onFetch={getData} loading={loading} pageSize={pageSize} scroll={{ y: 450 }}
        dataSource={data} pagination={false} rowKey='name' />
      <ConfirmOperation title={sureTip} ref={confirmOperationRef} callback={() => {
        callback()
      }} />
    </PageContainer>
  );
};

export default TableList;
